package com.ukefu.webim.config.web;

import java.io.IOException;
import java.util.*;

import com.ukefu.webim.service.repository.*;
import com.ukefu.webim.web.model.*;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.DicSegment;
import com.ukefu.util.sensitive.SensitiveFilter;
import com.ukefu.webim.service.cache.CacheHelper;

@Component
@ImportResource("classpath:config/applicationContext-snaker.xml")
public class StartedEventListener implements ApplicationListener<ContextRefreshedEvent> {
	
	@Value("${web.upload-path}")
    private String path;
	
	@Value("${spring.datasource.driver-class-name}")
    private String drivers_class_name;
	
	private SysDicRepository sysDicRes;
	
	private BlackListRepository blackListRes ;

	@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
    	ConvertUtils.register(new DateConverter(null), java.util.Date.class);
    	if(UKDataContext.getContext() == null){
    		UKDataContext.setApplicationContext(event.getApplicationContext());
    	}
    	sysDicRes = event.getApplicationContext().getBean(SysDicRepository.class) ;
    	blackListRes = event.getApplicationContext().getBean(BlackListRepository.class) ;
    	List<SysDic> sysDicList = sysDicRes.findAll() ;
    	for(SysDic dic : sysDicList){
    		CacheHelper.getSystemCacheBean().put(dic.getId(), dic, dic.getOrgi());
			if(dic.getParentid().equals("0")){
				List<SysDic> sysDicItemList = new ArrayList<SysDic>();
				for(SysDic item : sysDicList){
					if(item.getDicid()!=null && item.getDicid().equals(dic.getId())){
						sysDicItemList.add(item) ;
					}
				}
				Collections.sort(sysDicItemList , new Comparator<SysDic>() {
					@Override
					public int compare(SysDic o1, SysDic o2) {
						return o1!=null && o2!=null ? o1.getSortindex() - o2.getSortindex() : o1!=null ? 1 : o2!=null ? 1 : 0;
					}
				});
				CacheHelper.getSystemCacheBean().put(dic.getCode(), sysDicItemList, dic.getOrgi());
			}
		}
    	List<BlackEntity> blackList = blackListRes.findByOrgi(UKDataContext.SYSTEM_ORGI) ;
    	for(BlackEntity black : blackList){
    		if(!StringUtils.isBlank(black.getUserid())) {
	    		if(black.getEndtime()==null || black.getEndtime().after(new Date())){
	    			CacheHelper.getSystemCacheBean().put(black.getUserid(), black, black.getOrgi());
	    		}
    		}
    	}
    	/**
    	 * 加载系统全局配置
    	 */
    	SystemConfigRepository systemConfigRes = event.getApplicationContext().getBean(SystemConfigRepository.class) ;
    	List<SystemConfig> configList = systemConfigRes.findByOrgi(UKDataContext.SYSTEM_ORGI) ;
		SystemConfig systemConfig = null;
    	if(configList != null && configList.size() > 0){
			systemConfig = configList.get(0);
    		CacheHelper.getSystemCacheBean().put("systemConfig", systemConfig, UKDataContext.SYSTEM_ORGI);
    	}
    	GenerationRepository generationRes = event.getApplicationContext().getBean(GenerationRepository.class) ;
    	List<Generation> generationList = generationRes.findAll() ;
    	for(Generation generation : generationList){
    		//NOTE 分租户
    		CacheHelper.getSystemCacheBean().setAtomicLong(UKDataContext.ModelType.WORKORDERS.toString() + "_" + generation.getOrgi(), generation.getStartinx());
    	}
    	
    	UKTools.initSystemArea();
    	
    	UKTools.initSystemSecField(event.getApplicationContext().getBean(TablePropertiesRepository.class));
    	//UKTools.initAdv();//初始化广告位

		//NOTE 初始化租户授权模块
		if(systemConfig != null){
			if(systemConfig.isEnabletneant()){
				TenantRepository tenantRepository = event.getApplicationContext().getBean(TenantRepository.class) ;
				if(tenantRepository != null){
					List<Tenant> tenantList = tenantRepository.findByDatastatus(false);
					for(Tenant tenant : tenantList){
						Map<String , Boolean> modelMap = UKDataContext.orgiModel.get(tenant.getTenantcode());
						if(modelMap == null || modelMap.size() == 0){
							modelMap = new HashMap<>();
						}
						if(StringUtils.isNotBlank(tenant.getModels())) {
							modelMap.clear();
							String[] modelsArr = tenant.getModels().split(",");
							for(String model : modelsArr) {
								modelMap.put(model, true) ;
							}
						}else{
							modelMap = new HashMap<>();
						}

						UKDataContext.orgiModel.put(tenant.getTenantcode(),modelMap);
					}
				}
			}
		}

    	/**
    	 * 初始化敏感词词库
    	 */
    	SensitiveFilter.getSensitiveFilter().initSensitiveWords();
    	
    	try {
			DicSegment.segment("") ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//初始化
    	
    	//把当前数据库类型放入缓存
		if(!StringUtils.isBlank(drivers_class_name) && CacheHelper.getSystemCacheBean().getCacheObject(UKDataContext.DRIVERS_CLASS_NAME.toString(), UKDataContext.SYSTEM_ORGI) == null) {
			CacheHelper.getSystemCacheBean().put(UKDataContext.DRIVERS_CLASS_NAME.toString(), drivers_class_name, UKDataContext.SYSTEM_ORGI);
		}
		
		//把预警用户放入缓存
		systemConfig = UKTools.getSystemConfig() ;
		if (systemConfig.isEnablereqlogwarning()) {
			if (!StringUtils.isBlank(systemConfig.getReqlogwarningtouser())) {
				UserRepository userRes = UKDataContext.getContext().getBean(UserRepository.class);
	    		List<User> userList = new ArrayList<User>();
	    		String[] userids = systemConfig.getReqlogwarningtouser().split(",");
	    		if (userids != null && userids.length >0) {
	    			for(String id : userids) {
	    				User ut = userRes.findById(id) ;
	    				userList.add(ut);
	    			}
				}
	    		CacheHelper.getSystemCacheBean().put(UKDataContext.SYSTEM_CACHE_WARNING_TOUSER, userList , UKDataContext.SYSTEM_ORGI);
			}
			SystemMessageRepository systemMessageRes = UKDataContext.getContext().getBean(SystemMessageRepository.class);
			if (!StringUtils.isBlank(systemConfig.getReqlogwarningemailid())) {//把预警邮件服务存入缓存
				SystemMessage systemMessage = systemMessageRes.findByIdAndOrgi(systemConfig.getReqlogwarningemailid(),UKDataContext.SYSTEM_ORGI) ;
	    		CacheHelper.getSystemCacheBean().put(systemConfig.getReqlogwarningemailid(), systemMessage , UKDataContext.SYSTEM_ORGI);
			}
			if (!StringUtils.isBlank(systemConfig.getReqlogwarningsmsid())) {//把预警短信服务存入缓存
				SystemMessage systemMessage = systemMessageRes.findByIdAndOrgi(systemConfig.getReqlogwarningsmsid(),UKDataContext.SYSTEM_ORGI) ;
	    		CacheHelper.getSystemCacheBean().put(systemConfig.getReqlogwarningsmsid(), systemMessage , UKDataContext.SYSTEM_ORGI);
			}
		}
		
    }
}